import java.util.LinkedList;
import java.util.Queue;

public class Solution297 {
    /**
     * 二叉树的序列号和反序列化
     */

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if (root == null) return "";
        StringBuilder sb = new StringBuilder();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            if (node == null) {
                sb.append("null").append(",");
                continue;
            }
            sb.append(node.val).append(",");
            queue.add(node.left);
            queue.add(node.right);
        }
        return sb.toString();
    }


    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if (data.equals("")) return null;
        String[] split = data.split(",");
        TreeNode head = new TreeNode(Integer.parseInt(split[0]));
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(head);
        int i = 1;
        while (!queue.isEmpty()){
            TreeNode node = queue.poll();
            if (split[i].equals("null")){
                i++;
            }else {
                node.left = new TreeNode(Integer.parseInt(split[i++]));
                queue.add(node.left);
            }
            if (split[i].equals("null")){
                i++;
            }else {
                node.right = new TreeNode(Integer.parseInt(split[i++]));
                queue.add(node.right);
            }
        }
        return head;
    }
}
